<template>
  <el-card style="border: 0;">
    <!-- 操作栏 -->
    <div class="park-header">
      <el-button type="primary" icon="Plus" size="small" @click="handleAdd">
        新增园区
      </el-button>
    </div>

    <!-- 筛选区 -->
    <el-form :inline="true" :model="filterForm" class="filter-form" style="margin-bottom: 15px;">
      <el-form-item label="园区名称">
        <el-input v-model="filterForm.name" @input="val => filterForm.name = val" placeholder="请输入园区名称" clearable />
      </el-form-item>
      <!-- <el-form-item label="所在城市">

        <el-select v-model="filterForm.city" @change="val => filterForm.city = val" placeholder="请选择城市" clearable
          style="width: 150px;">
          <el-option v-for="city in cities" :key="city" :label="city" :value="city" />
        </el-select>

      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="handleFilter">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="parkList" :border="true" style="width: 100%">
      <el-table-column prop="name" label="园区名称" :align="center" />
      <!-- <el-table-column prop="city" label="所在城市" :align="center" /> -->
      <el-table-column prop="address" label="详细地址" :align="center" />
      <el-table-column prop="area" label="占地面积(㎡)" :align="center" width="150" />
      <el-table-column prop="description" label="园区描述" show-overflow-tooltip :align="center" />
      <el-table-column prop="createTime" label="创建时间" :align="center" />
      <el-table-column label="默认园区" width="100" :align="center" v-if="isAdmin">
        <template #default="scope">
          <el-switch v-model="scope.row.isDefault" :active-value="true" :inactive-value="false"
            @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="地理信息" width="100" :align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleView(scope.row)">
            地理信息
          </el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="220" :align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
          <el-button size="small" type="primary" @click="handleViewBuildings(scope.row)">
            查看楼栋
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalParks" />
    </div>
  </el-card>
</template>

<script setup>
import { ref, watch, inject, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import request from '@/api/request';
import auth from '@/components/utils/auth';


//是否是超级管理员，超级管理员才有系统设置
const isAdmin = ref(false)

// 初始化
onMounted(() => {
  try {
    const userInfo = auth.getUserInfo()
    const roles = userInfo.roles
    // 判断是否是超级管理员
    isAdmin.value = roles.some(role => role.roleCode === 'admin');
  } catch (err) {

  }
});

const center = 'center'

// 状态管理
const currentPage = ref(1);
const pageSize = ref(10);
const totalParks = ref(0);
const parkList = ref([]);
const filterForm = ref({
  name: '',
  city: ''
});

// 城市列表
// const cities = ref([
//   '贵阳', '六盘水'
// ]);

// 注入数据和方法
const parkData = inject('parkData');
const fetchParkList = inject('fetchParkList');
const openParkForm = inject('openParkForm');
const emit = defineEmits(['view-buildings', 'view-park']);

// 监听参数变化，重新加载数据
watch([currentPage, pageSize, () => filterForm.value], loadParkList, { immediate: true });

// 加载园区列表
function loadParkList() {
  fetchParkList(filterForm.value, currentPage.value, pageSize.value).then(data => {
    // 应用筛选
    parkList.value = data.list;
    totalParks.value = data.total;
  });
}

// 处理新增
const handleAdd = () => {
  openParkForm();
};

// 处理编辑
const handleEdit = (row) => {
  openParkForm(row);
};
// 处理删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除当前园区吗?')
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      request.get('/park/remove/' + id).then(data => {
        if (data.success) {
          loadParkList();
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(data.message);
        }
        loading.close()
      }).catch(err => {
        ElMessage.error('删除异常' + err);
        loading.close()
      })
    })
    .catch(() => {
      // catch error
    }).finally(() => {
    })
};

// 处理开关状态变化
const handleStatusChange = async (row) => {
  request.get('/park/modifyDefaultPark',{
    params: {
      parkId: row.id,
      isDefault: row.isDefault
    }
  }).then(data => {
    if (data.success) {
      loadParkList();
      ElMessage.success('修改成功');
    } else {
      ElMessage.error("修改失败");
    }
  }).catch(err => {
    ElMessage.error('修改失败' + err);
  })
};

// 查看楼栋
const handleViewBuildings = (row) => {
  emit('view-buildings', row);
};
const handleView = (row) => {
  emit('view-park', row);
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1;
  loadParkList();
};

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    name: '',
    city: ''
  };
  currentPage.value = 1;
  loadParkList();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

defineExpose({ loadParkList }); // 暴露刷新方法给上层
</script>

<style scoped>
.park-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}

.filter-form {
  text-align: left;
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}
</style>
